<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/29 0029
 * Time: 14:48
 */
namespace app\index\controller;
use app\admin\model\ClockModel;
use app\admin\model\DepartmenModel;
use app\admin\model\LeaveModel;
use app\admin\model\ProductsModel;
use app\admin\model\ReleaseModel;
use app\admin\model\VoucherModel;
use think\Db;
use think\Exception;
use think\Request;
use app\index\model\Api as Apis;

class Api
{
    /**获取某公司的部门列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function departmenList(Request $request){
        $user = isSign();
        if(!$user){
            return json(['code'=>401,'msg'=>'未登陆']);
        }
        $company_id = $request->param('company_id',$user['company_id']);
        $data = DepartmenModel::getDepartmen()
            ->where('departmen_table.company_id',$company_id)
            ->select();
        return json(['code'=>200,'date'=>$data]);
    }

    /**申请职位
     * @param Request $request
     * @return array
     */
    public function apply(Request $request){
        $id = $request->param('id',null);
        if(!$id){
            return returns(404,'请输入你要查看的id');
        }
        //检测是否登录
        if(!$user = isSign()){
            return returns(401);
        }
        //检测积分是否足够
        $release = ReleaseModel::getRelease()
            ->where('post_release.id',$id)
            ->find();
        if($user['integral']<$release['integral_condition']){
            return returns(405,'积分不足');
        }
        if($release['position_id']==$user['post_id']){
            return returns(405,'你申请的职位和你的职位一样');
        }
        if($release['userid']==$user['id']){
            return returns(405,'你可以跟自己申请');
        }
//        return json($user);
        //检测是否已经申请
        $new = Db::name('news')
            ->where('receive_id',$release['userid'])
            ->where('send_out',$user['id'])
            ->where('news_type','post_release')
            ->where('table_id',$release['id'])
            ->find();
        if($new){
            return returns(405,'你已经申请了此职位');
        }
        //添加申请消息
        $news['receive_id'] = $release['userid'];
        $news['send_out']   = $user['id'];
        $news['news_type']  = 'post_release';
        $news['describe']   = $user['nickname']."申请职位:".$release['company_name'].'/'.$release['departmen_name'].'/'.$release['position_name'];
        $news['cretae_time']= time();
        $news['status']     = 0;
        $news['table_id']   = $release['id'];
        if(Db::name('news')->insert($news)){
            return returns(200,'申请成功,待审核');
        }else{
            return returns(403,'申请失败，请稍后再试');
        }
    }

    /**兑换各种券
     * @param Request $request
     * @return array
     */
    public function quan(Request $request){
        if(!$user = isSign()){
            return returns(401);
        }
        $id = $request->param('id',null);
        if(!$id){
            return returns(405,'请输入要兑换的id');
        }
        //获取要兑换的id组成的数组
        $id = explode(',',trim($id,','));
        $type = $request->param('type',null);
        if(!$type){
            return returns(405,'请输入要兑换的类型');
        }
        //获取兑换的券的类型
        $voucher = VoucherModel::getVoucher()->where('id',$type)->find();
        //获取要兑换券的积分
        $fen = $voucher['required_integral']*count($id);
        if($user['integral']<$fen){
            return returns(407,'积分不足');
        }
        //return $voucher['voucher_type'];
//        $array = Db::name('punch_clock')->where('id','in',$id)->update([$voucher['voucher_type']=>0]);
//        return json($array);
        //开启事务1.自己减去积分，2.加入积分变更表，3.修改打卡记录的状态
        Db::startTrans();
        try{
            Db::name('punch_clock')->where('id','in',$id)->update([$voucher['voucher_type']=>0]);
            Db::name('integral_change')->insert([
                'userid'=>$user['id'],
                'company_id'=>$user['company_id'],
                'department_id' =>$user['department_id'],
                'number'        =>0-$fen,
                'change_describes'=>'兑换'.$voucher['voucher_name'],
                'operator'=>0,
                'create_time'=>time()
            ]);
            $fen = $user['integral']-$fen;
            Db::name('user')->where('id',$user['id'])->update(['integral'=>$fen]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return returns(405,'兑换失败');
        }
//        $bool = Db::transaction(function ($user,$fen,$id,$voucher){
//            Db::name('user')->where('id',$user['id'])->update(['integral'=>$fen]);
//            Db::name('punch_clock')->where('id','in',$id)->update($voucher['voucher_type'],0);
//        });
        $user['integral'] = $fen;
        session('user',$user);
        return returns(200,'兑换成功');
    }

    /**带条件查询公司产品
     * @param Request $request
     * @return array|\think\response\Json
     */
    public function products(Request $request){
        $data = $request->param();
        if(!$user=isSign()){
            return returns(401);
        }
        if($data['end']){
            $data = ProductsModel::getProducts()
                ->where('required_integral','>=',$data['start'])
                ->where('required_integral','<=',$data['end'])
                ->select();
        }else{
            $data = ProductsModel::getProducts()
                ->where('required_integral','>=',$data['start'])
                ->select();
        }
        return json($data);
    }

    /**兑换公司产品
     * @param Request $request
     * @return array
     */
    public function products_order(Request $request){
        $id = $request->param('id',null);
        $num = $request->param('num',1);
        if(!$user= isSign()){
            return returns();
        }
        if(!$id){
            return returns(403,'请输入要兑换物品');
        }
        //获取对应的公司产品
        $products = ProductsModel::getProducts()->where('id',$id)->find();
        $fen = $products['required_integral']*$num;
        if($user['integral']<$fen){
            return returns(405,'积分不足');
        }
        //组装订单
        $order['products_id']    = $id;
        $order['number']         = $num;
        $order['userid']         = $user['id'];
        $order['company_id']     = $user['company_id'];
        $order['department_id']  = $user['department_id'];
        $order['status']         = 0;

//组装积分变更
        $change['userid']        = $user['id'];
        $change['company_id']    = $user['company_id'];
        $change['department_id'] = $user['department_id'];
        $change['number']        = 0-$fen;
        $change['change_describes'] = '购买'.$products['product_name'].$num.'件';
        $change['operator']      = 0;
        $change['create_time']   = time();
        //开启事务
        Db::startTrans();
        try{
            Db::name('products_order')->insert($order);
            Db::name('user')->where('id',$user['id'])->update(['integral'=>$user['integral']-$fen]);
            Db::name('integral_change')->insert($change);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return returns(402,'兑换失败');
        }
        $user['integral'] = $user['integral']-$fen;
        session('user',$user);
        return returns(200,'兑换成功');
    }

    /**对职位申请的处理
     * @param Request $request
     * @return array
     */
    public function zhiweiHuifu(Request $request){
        $type = $request->param('type',null);
        if(!$type){
            return returns(403,'请输入你回复的类型');
        }
        //检测登录和参数
        $id = $request->param('id',null);
        if(!$id){
            return returns(403,'请输入你回复的id');
        }
        if(!$user=isSign()){
            return returns();
        }
        //获取消息详细内容
        $newss = Db::name('news')->where('id',$id)->find();
        //获取职位招聘信息
        $release = ReleaseModel::getRelease()->where('post_release.id',$newss['table_id'])->find();
//        return json($release);
        //查看是否已经处理了这条数据
        $str = $user['nickname'].'邀请你'.date('Y-m-d',$release['end_time']).'参加'.$release['company_name'].'/'.$release['departmen_name'].'面试';
        $str1 = $user['nickname'].'驳回了你申请职位:'.$release['company_name'].'/'.$release['departmen_name'].'/'.$release['position_name'].'的请求';
        $fen   = Db::name('news')
            ->where('receive_id',$newss['send_out'])
            ->where('send_out',$newss['receive_id'])
            ->where('cretae_time','<',$release['end_time'])
            ->where('cretae_time','>',$release['create_time'])
            ->where('table_id',$newss['table_id'])
            ->where('describe',$str)
            ->whereOr('describe',$str1)
            ->select();
        if(count($fen)){
            return returns(403,'你已经处理了这个请求');
        }
        //编辑消息
        $news['receive_id'] = $newss['send_out'];
        $news['send_out'] = $newss['receive_id'];
        $news['news_type'] = '普通';
        $news['table_id']  = $newss['table_id'];
        $news['cretae_time'] = time();
        $news['status'] = 0;
        //驳回和邀请面试的处理
        if($type=='mianshi'){
            $news['describe'] = $str;
            if(Db::name('news')->insert($news)){
                return returns(200,'邀请成功');
            }else{
                return returns(403,'邀请失败');
            }
        }else{
            $news['describe'] = $str1;
            if(Db::name('news')->insert($news)){
                return returns(200,'驳回成功');
            }else{
                return returns(403,'驳回失败');
            }
        }
    }

    /**同意和驳回请假条
     * @param Request $request
     * @return array
     */
    public function leave(Request $request){
        $data = $request->param();
        //检验数据合法性
        $val = val($data,['type|反馈类型'=>'require','id|要删除的数据'=>'require']);
        if(!$val['code']){
            return returns(405,$val['msg']);
        }
        //检测是否登录
        if(!$user= isSign()){
            return returns();
        }
        //获取请假条数据
        $jiou = LeaveModel::getLeave()->where('leave.id',$data['id'])->find();
        //如果处理了就返回
        if(!($jiou['status']==0)){
            return returns(403,'本消息已经处理');
        }
//        return json($jiou);
        //组装消息
        $news['receive_id'] = $jiou['userid'];
        $news['send_out'] = $user['id'];
        $news['news_type'] = '普通';
        $news['cretae_time'] = time();
        $news['status'] = 0;
        $news['table_id'] = '';
        if($data['type']=='驳回'){
            //如果驳回
            $news['describe'] = $user['nickname'].'驳回了你的请假请求';
            $bool = LeaveModel::updateLeave(['id'=>$jiou['id'],'status'=>2,'examine_time'=>time()]);
            if(!$bool){
                return returns(403,'驳回请假条失败');
            }
            if(Db::name('news')->insert($news)){
               return returns(200,'驳回请假条成功');
            }else{
                return returns(403,'驳回请假条失败');
            }
        }else{
            //如果同意
            $days = Apis::getLeaveTime($jiou['starttime'],$jiou['endtime'],$jiou['departmen_id']);
//            return json($days);
            if(!$days){
                //如果请假不在上班时间内
                $news['describe'] = $user['nickname'].'驳回了你的请假请求';
                $bool = LeaveModel::updateLeave(['id'=>$jiou['id'],'status'=>2,'examine_time'=>time()]);
                if(!$bool){
                    return returns(403,'驳回请假条失败');
                }
                if(Db::name('news')->insert($news)){
                    return returns(200,'请假时间不在上班时间内,已驳回');
                }else{
                    return returns(406,'请假时间不在上班时间内未驳回');
                }

            }
            //如果请假在上班时间内
            $news['describe'] = $user['nickname'].'同意了你的请假请求';
            $bool = LeaveModel::updateLeave(['id'=>$jiou['id'],'status'=>1,'examine_time'=>time()]);
            if(!$bool){
                return returns(403,'同意请假条失败');
            }
            $clock['userid'] = $jiou['userid'];
            $clock['company_id'] = $jiou['company_id'];
            $clock['departmen_id'] = $jiou['departmen_id'];
            $clock['overtime'] = 0;
            $clock['late'] = 0;
            $clock['early_retreat'] = 0;
            $clock['leave'] = 1;
            $clock['absenteeism'] = 0;
            //将请假时间都上班都打卡
            if(count($days['toWork'])){
                foreach ($days['toWork'] as $value){
                    $clock['punch_type'] = 'toWork';
                    $clock['create_time'] = $value;
                    ClockModel::addClock($clock);
                }
            }
            //将请假时间下班都打卡
            if(count($days['offWork'])){
                foreach ($days['offWork'] as $value){
                    $clock['punch_type'] = 'offWork';
                    $clock['create_time'] = $value;
                    ClockModel::addClock($clock);
                }
            }
            return returns(200,'同意假条成功');
        }
    }
}